/**
 * 日期工具函数
 */

/**
 * 格式化日期
 */
export function formatDate(date: Date | string, format: string = 'YYYY-MM-DD'): string {
  const d = new Date(date)
  
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  
  return format
    .replace('YYYY', String(year))
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

/**
 * 格式化时间
 */
export function formatTime(time: string): string {
  return time.substring(0, 5) // HH:MM
}

/**
 * 获取今天的日期字符串
 */
export function getTodayString(): string {
  return formatDate(new Date(), 'YYYY-MM-DD')
}

/**
 * 获取本周的开始和结束日期
 */
export function getWeekRange(date: Date = new Date()): { start: Date; end: Date } {
  const start = new Date(date)
  const day = start.getDay()
  const diff = start.getDate() - day + (day === 0 ? -6 : 1) // 周一为一周开始
  start.setDate(diff)
  start.setHours(0, 0, 0, 0)
  
  const end = new Date(start)
  end.setDate(start.getDate() + 6)
  end.setHours(23, 59, 59, 999)
  
  return { start, end }
}

/**
 * 获取本月的开始和结束日期
 */
export function getMonthRange(date: Date = new Date()): { start: Date; end: Date } {
  const start = new Date(date.getFullYear(), date.getMonth(), 1)
  const end = new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59, 999)
  
  return { start, end }
}

/**
 * 检查日期是否为今天
 */
export function isToday(date: Date | string): boolean {
  const today = new Date()
  const targetDate = new Date(date)
  
  return today.getFullYear() === targetDate.getFullYear() &&
         today.getMonth() === targetDate.getMonth() &&
         today.getDate() === targetDate.getDate()
}

/**
 * 检查日期是否在指定范围内
 */
export function isDateInRange(date: Date | string, start: Date | string, end: Date | string): boolean {
  const targetDate = new Date(date)
  const startDate = new Date(start)
  const endDate = new Date(end)
  
  return targetDate >= startDate && targetDate <= endDate
}

/**
 * 添加天数到日期
 */
export function addDays(date: Date | string, days: number): Date {
  const result = new Date(date)
  result.setDate(result.getDate() + days)
  return result
}

/**
 * 添加月份到日期
 */
export function addMonths(date: Date | string, months: number): Date {
  const result = new Date(date)
  result.setMonth(result.getMonth() + months)
  return result
}

/**
 * 获取两个日期之间的天数差
 */
export function getDaysDiff(date1: Date | string, date2: Date | string): number {
  const d1 = new Date(date1)
  const d2 = new Date(date2)
  const timeDiff = Math.abs(d2.getTime() - d1.getTime())
  return Math.ceil(timeDiff / (1000 * 3600 * 24))
}
